<?php 

abstract class ActiveRecordSystem {
	
    protected $tablename;
    public $dbobj;
    
    protected $dbcnx;
    
    
    /**
     * Points to $DB
     */
    public function __construct() {
        global $DB;
        $this->dbcnx = $DB;
    }


    public function insert() {

        $this->dbobj->id = $this->dbcnx->insertObject($this->tablename, $this->dbobj);
        return $this->dbobj->id;
    }


    public function update() {

        if (empty($this->dbobj->id) || !$this->dbobj->id) {
            return false;
        }

        $sets = clone $this->dbobj;
        unset($sets->id);

        return $this->dbcnx->updateObject($this->tablename, $sets, $this->dbobj->id);
    }


    public function get() {

        if (empty($this->dbobj->id)) {
            return false;
        }

        $sql = "SELECT * FROM ".$this->tablename." WHERE id = ?";
        $this->dbobj = $this->dbcnx->selectResponse($sql, array($this->dbobj->id));

        return $this->dbobj;
    }

    
    public function getBy($where) {
        
        if (is_object($where)) {
            $where = (Array)$where;
        }
        
        $sql = "SELECT * FROM ".$this->tablename." WHERE ";
        foreach ($where as $key => $value) {
            $fields[] = " ".$key." = ?" ;
            $params[] = $value;
        }
        $sql = $sql.implode(' AND ', $fields);
        
        $this->dbobj = $this->dbcnx->selectResponse($sql, $params);
        
        // Will return false if it doesn't exists
        return $this->dbobj;
    }
	
}
